using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Book.Blog.Core.DTOs;
using Book.Blog.Core.Entities;
using Book.Blog.Core.Interfaces;
using System.Linq;

namespace Book.Blog.API.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class CategoriesController : ControllerBase
    {
        private readonly IRepository<Category> _categoryRepository;
        private readonly IUnitOfWork _unitOfWork;

        public CategoriesController(
            IRepository<Category> categoryRepository,
            IUnitOfWork unitOfWork)
        {
            _categoryRepository = categoryRepository;
            _unitOfWork = unitOfWork;
        }

        /// <summary>
        /// 获取所有分类列表
        /// </summary>
        /// <returns>分类列表</returns>
        [HttpGet]
        public async Task<ActionResult<IEnumerable<CategoryListDTO>>> GetCategories()
        {
            var categories = await _unitOfWork.Categories.GetAllAsync();
            return Ok(categories
                .OrderBy(c => c.SortOrder)
                .Select(c => new CategoryListDTO
                {
                    Id = c.Id,
                    Name = c.Name,
                    Description = c.Description,
                    Slug = c.Slug,
                    SortOrder = c.SortOrder,
                    PostCount = c.PostCount
                }));
        }

        /// <summary>
        /// 根据ID获取分类详情
        /// </summary>
        /// <param name="id">分类ID</param>
        /// <returns>分类详情</returns>
        [HttpGet("{id}")]
        public async Task<ActionResult<CategoryDTO>> GetCategory(Guid id)
        {
            var category = await _unitOfWork.Categories.GetByIdAsync(id);
            if (category == null)
            {
                return NotFound();
            }

            return new CategoryDTO
            {
                Id = category.Id,
                Name = category.Name,
                Description = category.Description,
                Slug = category.Slug,
                SortOrder = category.SortOrder,
                PostCount = category.PostCount,
                CreatedTime = category.CreatedTime,
                UpdatedTime = category.UpdatedTime
            };
        }

        /// <summary>
        /// 根据slug获取分类详情
        /// </summary>
        /// <param name="slug">分类slug</param>
        /// <returns>分类详情</returns>
        [HttpGet("slug/{slug}")]
        public async Task<ActionResult<CategoryDTO>> GetCategoryBySlug(string slug)
        {
            var categories = await _unitOfWork.Categories.GetAllAsync();
            var category = await categories.AsQueryable().FirstOrDefaultAsync(c => c.Slug == slug);
            if (category == null)
            {
                return NotFound();
            }

            return new CategoryDTO
            {
                Id = category.Id,
                Name = category.Name,
                Description = category.Description,
                Slug = category.Slug,
                SortOrder = category.SortOrder,
                PostCount = category.PostCount,
                CreatedTime = category.CreatedTime,
                UpdatedTime = category.UpdatedTime
            };
        }

        /// <summary>
        /// 创建新分类（需管理员权限）
        /// </summary>
        /// <param name="model">分类信息</param>
        /// <returns>新建分类详情</returns>
        /// <remarks>
        /// 示例请求:
        /// {
        ///   "name": "技术",
        ///   "description": "技术相关的文章",
        ///   "slug": "tech",
        ///   "sortOrder": 1
        /// }
        /// </remarks>
        [HttpPost]
        [Authorize(Roles = "Admin")]
        public async Task<ActionResult<CategoryDTO>> CreateCategory(CreateCategoryDTO model)
        {
            var categories = await _unitOfWork.Categories.GetAllAsync();
            var existingCategory = await categories.AsQueryable().FirstOrDefaultAsync(c => c.Slug == model.Slug);
            if (existingCategory != null)
            {
                return BadRequest("分类已存在");
            }

            var category = new Category
            {
                Name = model.Name,
                Description = model.Description,
                Slug = model.Slug,
                SortOrder = model.SortOrder
            };

            await _unitOfWork.Categories.AddAsync(category);
            await _unitOfWork.SaveChangesAsync();

            return CreatedAtAction(nameof(GetCategory), new { id = category.Id }, new CategoryDTO
            {
                Id = category.Id,
                Name = category.Name,
                Description = category.Description,
                Slug = category.Slug,
                SortOrder = category.SortOrder,
                PostCount = category.PostCount,
                CreatedTime = category.CreatedTime,
                UpdatedTime = category.UpdatedTime
            });
        }

        /// <summary>
        /// 更新分类（需管理员权限）
        /// </summary>
        /// <param name="id">分类ID</param>
        /// <param name="model">分类信息</param>
        /// <returns>无内容</returns>
        /// <remarks>
        /// 示例请求:
        /// {
        ///   "name": "技术",
        ///   "description": "技术相关的文章",
        ///   "slug": "tech",
        ///   "sortOrder": 1
        /// }
        /// </remarks>
        [HttpPut("{id}")]
        [Authorize(Roles = "Admin")]
        public async Task<IActionResult> UpdateCategory(Guid id, UpdateCategoryDTO model)
        {
            var category = await _unitOfWork.Categories.GetByIdAsync(id);
            if (category == null)
            {
                return NotFound();
            }

            // 检查新的 slug 是否已存在
            if (model.Slug != category.Slug)
            {
                var categories = await _unitOfWork.Categories.GetAllAsync();
                var existingCategory = await categories.AsQueryable().FirstOrDefaultAsync(c => c.Slug == model.Slug);
                if (existingCategory != null)
                {
                    return BadRequest("分类已存在");
                }
            }

            category.Name = model.Name;
            category.Description = model.Description;
            category.Slug = model.Slug;
            category.SortOrder = model.SortOrder;
            category.UpdatedAt = DateTime.UtcNow;

            await _unitOfWork.SaveChangesAsync();

            return NoContent();
        }

        /// <summary>
        /// 删除分类（需管理员权限）
        /// </summary>
        /// <param name="id">分类ID</param>
        /// <returns>无内容</returns>
        [HttpDelete("{id}")]
        [Authorize(Roles = "Admin")]
        public async Task<IActionResult> DeleteCategory(Guid id)
        {
            var category = await _unitOfWork.Categories.GetByIdAsync(id);
            if (category == null)
            {
                return NotFound();
            }

            // 先移除所有关联的文章
            foreach (var post in category.Posts.ToList())
            {
                post.Category = null;
                post.CategoryId = Guid.Empty;
            }

            await _unitOfWork.Categories.DeleteAsync(category);
            await _unitOfWork.SaveChangesAsync();

            return NoContent();
        }
    }
} 